package org.etnaframework.module.web.api;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 记录HTTP请求日志专用
 *
 * @author jasyaf
 * @since 2024-09-21
 */
class WebAccessLog {

    static final Logger log = LoggerFactory.getLogger(WebAccessLog.class);

    private final IWebAccessLogCustomizer accessLogCustomizer;

    public WebAccessLog(IWebAccessLogCustomizer accessLogCustomizer) {
        this.accessLogCustomizer = accessLogCustomizer;
    }

    /**
     * 判断是否需要记录日志，如果需要记录就记录请求日志
     */
    void save(HttpServletRequest request, HttpServletResponse response, String path, long startTime) {
        if (accessLogCustomizer.needToSaveLog(request, response, path)) {
            long elapsed = System.currentTimeMillis() - startTime;
            String accessLog = accessLogCustomizer.createAccessLog(request, response, elapsed);
            log.info(accessLog);
        }
    }
}
